package cfca.seal.web.action.log;

import cfca.seal.bean.AdminUser;
import cfca.seal.bean.OperationLog;
import cfca.seal.common.Page;
import cfca.seal.exception.CodeException;
import cfca.seal.mananger.OperationLogManager;
import cfca.seal.system.Env;
import cfca.seal.util.StringUtil;
import cfca.seal.util.TimeUtil;
import cfca.seal.web.service.OperationLogService;
import cfca.seal.web.system.SessionManager;
import com.csvreader.CsvWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping({"/operationLog"})
public class OperationLogAction
{

  @Resource
  private OperationLogService operationLogService;
  private static final Logger log = LoggerFactory.getLogger("web_sys");

  @RequestMapping({"/v_list"})
  public String getAll(OperationLog operationLog, String pageNo, ModelMap modelMap, HttpServletRequest request) throws CodeException {
    try {
      AdminUser adminUser = SessionManager.getManager(request);
      Page page = this.operationLogService.getAll(operationLog, pageNo, adminUser);
      modelMap.put("page", page);
      modelMap.put("log", operationLog);
      return "sys/log/list.html";
    } catch (Exception e) {
      log.error("日志查询出现系统错误", e);
      throw new CodeException("C0001", e);
    }
  }

  @RequestMapping({"/v_archive"})
  public String archiveView(OperationLog operationLog, String pageNo, ModelMap modelMap, HttpServletRequest request) throws CodeException {
    try {
      if ((StringUtil.isNotEmpty(operationLog.getArchiveYear())) && (StringUtil.isNotEmpty(operationLog.getArchiveMonth()))) {
        if ((!StringUtil.isNumeric(operationLog.getArchiveYear())) || (!StringUtil.isNumeric(operationLog.getArchiveMonth())) || (Integer.valueOf(operationLog.getArchiveMonth()).intValue() < 1) || (Integer.valueOf(operationLog.getArchiveMonth()).intValue() > 12))
        {
          throw new CodeException("C8007", "归档操作日志的年份和月份不能为空，且非零正整数");
        }
        Calendar time = Calendar.getInstance();
        time.clear();
        time.set(1, Integer.valueOf(operationLog.getArchiveYear()).intValue());
        time.set(2, Integer.valueOf(operationLog.getArchiveMonth()).intValue() - 1);
        int day = time.getActualMaximum(5);

        String month = operationLog.getArchiveMonth().length() == 1 ? "0" + operationLog.getArchiveMonth() : operationLog.getArchiveMonth();
        if (TimeUtil.getCurrentTimeToString().substring(0, 7).equals(operationLog.getArchiveYear() + "-" + month)) {
          throw new CodeException("C8008", "无法归档当月操作日志");
        }
        operationLog.setStartTime(operationLog.getArchiveYear() + "-" + month + "-01 00:00:00");
        operationLog.setEndTime(operationLog.getArchiveYear() + "-" + month + "-" + day + " 23:59:59");
      }

      AdminUser adminUser = SessionManager.getManager(request);
      Page page = this.operationLogService.getAll(operationLog, pageNo, adminUser);
      modelMap.put("page", page);
      modelMap.put("log", operationLog);

      return "sys/log/archive.html";
    } catch (CodeException ce) {
      log.error("日志归档查询出现系统错误", ce);
      throw new CodeException(ce.getCode(), ce.getMessage());
    } catch (Exception e) {
      log.error("日志归档查询出现系统错误", e);
      throw new CodeException("C0001", e);
    }
  }

  @RequestMapping({"/o_archive"})
  public String archive(OperationLog operationLog, String pageNo, ModelMap modelMap, HttpServletRequest request) throws CodeException {
    OperationLog opeLog = OperationLogManager.getInstance(request, "归档操作日志", "归档", "", "归档操作日志", null);
    try {
      if ((StringUtil.isEmpty(operationLog.getArchiveYear())) || (StringUtil.isEmpty(operationLog.getArchiveMonth()))) {
        throw new CodeException("C8007", "归档操作日志的年份和月份不能为空，且非零正整数");
      }
      if ((!StringUtil.isNumeric(operationLog.getArchiveYear())) || (!StringUtil.isNumeric(operationLog.getArchiveMonth())) || (Integer.valueOf(operationLog.getArchiveMonth()).intValue() < 1) || (Integer.valueOf(operationLog.getArchiveMonth()).intValue() > 12))
      {
        throw new CodeException("C8007", "归档操作日志的年份和月份不能为空，且非零正整数");
      }
      String month = operationLog.getArchiveMonth().length() == 1 ? "0" + operationLog.getArchiveMonth() : operationLog.getArchiveMonth();
      String yearAndMonth = operationLog.getArchiveYear() + "-" + month;
      opeLog.setDescription(opeLog.getDescription() + ":" + yearAndMonth);
      opeLog.setObjectId(yearAndMonth);

      if (TimeUtil.getCurrentTimeToString().substring(0, 7).equals(yearAndMonth)) {
        throw new CodeException("C8008", "无法归档当月操作日志");
      }
      Calendar time = Calendar.getInstance();
      time.clear();
      time.set(1, Integer.valueOf(operationLog.getArchiveYear()).intValue());
      time.set(2, Integer.valueOf(operationLog.getArchiveMonth()).intValue() - 1);
      int day = time.getActualMaximum(5);
      operationLog.setStartTime(yearAndMonth + "-01 00:00:00");
      operationLog.setEndTime(yearAndMonth + "-" + day + " 23:59:59");

      AdminUser adminUser = SessionManager.getManager(request);
      List list = this.operationLogService.getAllForArchive(operationLog, adminUser);

      String archiveLogDir = Env.configDir + File.separator + "archive" + File.separator + yearAndMonth;
      File uploadFilesFlag = new File(archiveLogDir);
      if (!uploadFilesFlag.isDirectory()) {
        uploadFilesFlag.mkdirs();
      }
      String archiveLogFileName = TimeUtil.getCurrentTimeToString().replace("-", "").replace(":", "").replace(" ", "") + ".csv";
      writeToCsvFiles(list, archiveLogDir + File.separator + archiveLogFileName);

      this.operationLogService.delete(operationLog, adminUser);

      Page page = new Page(0);
      page.setBeans(new ArrayList());
      modelMap.put("page", page);
      modelMap.put("log", operationLog);
      String resultInfo = "操作成功 归档日志数量(条数)：" + list.size();
      modelMap.put("resultInfo", resultInfo);

      return "sys/log/archive.html";
    } catch (CodeException ce) {
      opeLog.setResult(10);
      log.error("日志归档出现系统错误", ce);
      throw new CodeException(ce.getCode(), ce.getMessage());
    } catch (Exception e) {
      opeLog.setResult(10);
      log.error("日志归档出现系统错误", e);
      throw new CodeException("C0001", e);
    } finally {
      this.operationLogService.addOperationLog(opeLog);
    }
  }

  private void writeToCsvFiles(List<OperationLog> logs, String path)
  {
    try {
      CsvWriter wr = new CsvWriter(path, ',', Charset.forName("GBK"));
      String[] head = { "操作时间", "操作功能", "操作类型", "操作对象", "操作者", "操作描述", "所属企业", "操作结果" };
      wr.writeRecord(head);

      for (OperationLog log : logs) {
        String[] contents = { TimeUtil.getFormatDate(log.getCreateTime()), log.getApplicationName(), log.getType(), log.getObjectId(), log.getOperator(), log.getDescription(), log.getOrganizationId(), log.getResult() == 10 ? "操作失败" : "操作成功" };

        wr.writeRecord(contents);
      }
      wr.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}